注意:需要获取哪个打开main函数中的哪个

package com.hadoop.test;

import java.net.URI; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.DistributedFileSystem; import org.apache.hadoop.hdfs.protocol.DatanodeInfo;

public class HDFSAPITest {

/** *1 、获取HDFS文件系统 */ // 获取文件系统 public static FileSystem getFileSystem() throws Exception { // 读取配置文件 Configuration conf = new Configuration(); // 返回默认文件系统,如果在Hadoop集群下运行,使用此种方法可直接获取默认文件系统 // FileSystem fs = FileSystem.get(conf); // 指定的文件系统地址 URI uri = new URI("hdfs://master:9000"); // 返回指定的文件系统,如果在本地测试,需要使用此种方法获取文件系统 FileSystem fs = FileSystem.get(uri, conf); return fs; }

/** *2 、文件/目录的创建与删除 */ // 创建文件目录 public static void mkdir() throws Exception { // 获取文件系统 FileSystem fs = getFileSystem(); // 创建文件目录 fs.mkdirs(new Path("hdfs://master:9000/20191021/test")); // 释放资源 fs.close(); }

// 删除文件或者文件目录 public static void rmdir() throws Exception { // 返回FileSystem对象 FileSystem fs = getFileSystem(); // 删除文件或者文件目录 fs.delete(new Path("hdfs://master:9000/20191021/test"),true); // 释放资源 fs.close(); }

/** *3、 获取文件 */ // 获取目录下的所有文件 public static void ListAllFile() throws Exception { // 返回FileSystem对象 FileSystem fs = getFileSystem(); // 列出目录内容 FileStatus[] status = fs.listStatus(new Path("hdfs://master:9000/")); // 获取目录下的所有文件路径 Path[] listedPaths = FileUtil.stat2Paths(status); // 循环读取每个文件 for(Path p : listedPaths) { System.out.println(p); } // 释放资源 fs.close(); }

/** *4 、上传/下载文件 */ // 文件上传至HDFS public static void copyToHDFS() throws Exception { // 返回FileSystem对象 FileSystem fs = getFileSystem(); // 源文件路径是Linux下的路径,如果在Windows下测试,需要改写为Windows下的路径,比如E://Hadoop/weibo.txt //Path srcPath = new Path("/home/hadoop/weibo.txt"); Path srcPath = new Path("E://Hadoop/weibo.txt"); // 目的路径 Path dstPath = new Path("hdfs://master:9000/20191021/test"); // 实现文件上传 fs.copyFromLocalFile(srcPath, dstPath); // 释放资源 fs.close(); }

// 从HDFS下载文件 public static void getFile() throws Exception { // 返回FileSystem对象 FileSystem fs = getFileSystem(); // 源文件路径 Path srcPath = new Path("hdfs://master:9000/20191021/test/test.txt"); // 目的路径是Linux下的路径,如果在Windows下测试,需要改写为Windows下的路径,比如E://hadoop/djt/ //Path dstPath = new Path("/home/hadoop/"); Path dstPath = new Path("E://hadoop/djt/"); // 下载hdfs上的文件 fs.copyToLocalFile(srcPath, dstPath); // 释放资源 fs.close(); }

/** *5、 获取HDFS集群节点信息 */ // 获取HDFS集群节点信息 public static void getHDFSNodes() throws Exception { // 返回FileSystem对象 FileSystem fs = getFileSystem(); // 获取分布式文件系统 DistributedFileSystem hdfs = (DistributedFileSystem)fs; // 获取所有节点 DatanodeInfo[] DataNodeStats = hdfs.getDataNodeStats(); // 循环打印所有节点 for(int i=0;i<DataNodeStats.length;i++) { System.out.println("DataNode_"+i+"_Name:"+DataNodeStats[i].getHostName()); } } public static void main(String[] args) throws Exception { //mkdir(); //rmdir(); //ListAllFile(); //copyToHDFS(); //getFile(); //getHDFSNodes(); } }